<template>
  <Dialog v-model="panelDialog" title="手动创建任务" width="900px">
    <div class="panel-header">
      <div class="header-info">
        <el-icon class="info-icon"><EditPen /></el-icon>
        <el-text class="info-text">手动创建外呼任务，支持自定义配置</el-text>
      </div>
      <el-button class="clear-btn" link :icon="Delete" @click="clear">清空</el-button>
    </div>

    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(message, index) in messages"
          :key="index"
          class="message"
          :class="message.role"
        >
          <div class="message-wrapper" :class="message.role">
            <el-avatar :size="32" class="message-avatar" :src="AiImg" v-if="message.role == 'ai'" />
            <div class="message-content" :class="message.role">
              <div class="message-text">
                <!-- 处理包含按钮的HTML内容 -->
                <div
                  class="flex items-end"
                  v-html="processMessageContent(message.content, index)"
                ></div>
              </div>
              <div class="message-time">{{ formatTime(new Date()) }}</div>
            </div>
            <el-avatar
              class="message-avatar"
              :size="32"
              :src="WoImg"
              v-if="message.role == 'user'"
            />
          </div>
        </div>

        <div class="empty-state" v-if="messages.length == 0">
          <el-icon class="empty-icon"><Document /></el-icon>
          <p class="empty-text">开始手动创建任务</p>
          <p class="empty-subtext">详细描述您的外呼任务需求</p>
        </div>

        <div v-if="isLoading" class="message ai">
          <div class="message-wrapper ai">
            <el-avatar :size="32" class="message-avatar" :src="AiImg" />
            <div class="message-content ai">
              <div class="loading-container">
                <span class="loading-text">正在处理任务</span>
                <div class="loading-dots"> <span></span><span></span><span></span> </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input-container">
        <div class="input-wrapper">
          <el-input
            v-model="userInput"
            placeholder="请详细描述您要手动创建的外呼任务..."
            :disabled="isLoading"
            @keyup.enter="sendMessage"
            type="textarea"
            :rows="4"
            resize="none"
            class="chat-textarea"
          />
          <div class="input-actions">
            <div class="input-tip">
              <el-text size="small" type="info"> Enter 发送</el-text>
            </div>
            <el-button
              type="primary"
              class="send-button"
              :disabled="isLoading || !userInput.trim()"
              @click="sendMessage"
              :loading="isLoading"
            >
              <el-icon><Promotion /></el-icon>
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </Dialog>
</template>

<script setup>
import { getTenantId, getAccessToken } from '@/utils/auth'
import { generateUUID } from '@/utils'
import { emitter } from '@/utils/eventBus.ts'
import { Delete, EditPen, Document, Promotion } from '@element-plus/icons-vue'

import WoImg from '@/assets/img/wo.png'
import AiImg from '@/assets/img/ai.png'

const panelDialog = ref(false)
const userInput = ref('')
const messages = ref([])
const isLoading = ref(false)
const controller = ref(null)

const uuid = ref(null)
const baseUrl = ref('http://192.168.0.254:48081')

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理消息内容，替换按钮为美化的按钮
const processMessageContent = (content, messageIndex) => {
  if (!content) return ''

  // 使用正则表达式匹配button标签
  const buttonRegex = /<button[^>]*>(.*?)<\/button>/gi
  let buttonIndex = 0

  return content.replace(buttonRegex, (match, buttonText) => {
    // 生成唯一ID
    const buttonId = `btn_${messageIndex}_${buttonIndex}`

    // 检查按钮是否已被点击
    const isClicked = clickedButtons.value.has(buttonId)

    buttonIndex++

    // 如果已点击，返回隐藏的按钮或不返回按钮
    if (isClicked) {
      return `<span class="clicked-button-placeholder">✅ ${buttonText.trim()}</span>`
    }

    // 返回正常的按钮HTML
    return `
      <button 
        type="button"
        id="${buttonId}" 
        class="ai-action-button" 
        data-button-text="${buttonText.trim()}" 
        data-button-id="${buttonId}"
        onclick="window.handleAIButtonClick(this)"
      >
        <span class="button-icon">🚀</span>
        <span class="button-text">${buttonText.trim()}</span>
        <span class="button-arrow">→</span>
      </button>
    `
  })
}
const clickedButtons = ref(new Set())

// 处理AI按钮点击事件
const handleButtonClick = async (buttonText, buttonElement) => {
  if (isLoading.value) return

  // 获取按钮ID并记录为已点击
  const buttonId = buttonElement.getAttribute('data-button-id')
  if (buttonId) {
    clickedButtons.value.add(buttonId)
  }

  // 添加用户消息（显示点击的按钮内容）
  messages.value.push({
    role: 'user',
    content: `✅ ${buttonText}`
  })
  nextTick(() => {
    scrollToBottom()
  })
  // 发送按钮内容到接口
  await sendButtonMessage(buttonText)
}

// 发送按钮消息到接口
const sendButtonMessage = async (buttonText) => {
  isLoading.value = true
  controller.value = new AbortController()

  try {
    // 创建一个新的AI消息
    const aiMessageIndex = messages.value.length
    messages.value.push({
      role: 'ai',
      content: ''
    })

    const url = baseUrl.value + '/admin-api/ai/generateStreamAsString'

    // 使用fetch API发送按钮内容
    const response = await fetch(
      url + `?message=${encodeURIComponent(buttonText)}&chatId=${uuid.value}`,
      {
        method: 'GET',
        headers: {
          Accept: '*',
          Authorization: 'Bearer ' + getAccessToken(),
          'tenant-id': getTenantId()
        },
        signal: controller.value.signal
      }
    )

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 处理流式响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    let aiResponse = ''

    while (true) {
      const { done, value } = await reader.read()

      if (done) {
        break
      }

      buffer += decoder.decode(value, { stream: true })

      let eventEnd
      while ((eventEnd = buffer.indexOf('\n\n')) !== -1) {
        const eventStr = buffer.substring(0, eventEnd).trim()
        buffer = buffer.substring(eventEnd + 2)

        if (!eventStr.startsWith('data:')) continue

        const dataStr = eventStr.replaceAll('data:', '').trim()

        if (dataStr === '[complete]') {
          emitter.emit('refreshAiTask')
        }

        if (dataStr === '[complete]') continue

        try {
          const content = dataStr

          if (content && content != '[complete]') {
            aiResponse += content
            messages.value[aiMessageIndex].content = aiResponse
            nextTick(() => {
              scrollToBottom()
            })
          }
        } catch (e) {
          console.error('解析JSON失败:', e, '数据:', dataStr)
        }
      }
    }

    // 处理缓冲区中剩余的数据
    if (buffer.trim()) {
      const remainingData = buffer.trim()
      if (remainingData.startsWith('data:')) {
        const dataStr = remainingData.substring(5).trim()
        try {
          const content = dataStr
          if (content && content.trim()) {
            aiResponse += content
            messages.value[aiMessageIndex].content = aiResponse
          }
        } catch (e) {
          console.error('解析剩余数据失败:', e)
        }
      }
    }
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Request was cancelled')
    } else {
      console.error('Error:', error)
      messages.value.push({
        role: 'system',
        content: `发生错误: ${error.message}`
      })
    }
  } finally {
    isLoading.value = false
    controller.value = null
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  // 添加用户消息到对话历史
  const userMessage = userInput.value.trim()

  messages.value.push({
    role: 'user',
    content: userMessage
  })
  await nextTick(() => {
    scrollToBottom()
  })
  // 清空输入框
  userInput.value = ''

  // 设置加载状态
  isLoading.value = true

  // 创建一个新的AbortController，用于取消请求
  controller.value = new AbortController()

  try {
    // 创建一个新的AI消息
    const aiMessageIndex = messages.value.length
    messages.value.push({
      role: 'ai',
      content: ''
    })

    const url = baseUrl.value + '/admin-api/ai/generateStreamAsString'

    // 使用fetch API代替axios
    const response = await fetch(
      url + `?message=${encodeURIComponent(userMessage)}&chatId=${uuid.value}`,
      {
        method: 'GET',
        headers: {
          Accept: '*',
          Authorization: 'Bearer ' + getAccessToken(),
          'tenant-id': getTenantId()
        },
        signal: controller.value.signal
      }
    )

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 处理流式响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    let aiResponse = '' // 用于累积AI的响应内容

    while (true) {
      const { done, value } = await reader.read()

      if (done) {
        break
      }

      // 解码数据并添加到缓冲区
      buffer += decoder.decode(value, { stream: true })

      // 处理缓冲区中的所有完整事件
      let eventEnd
      while ((eventEnd = buffer.indexOf('\n\n')) !== -1) {
        const eventStr = buffer.substring(0, eventEnd).trim()
        buffer = buffer.substring(eventEnd + 2)

        if (!eventStr.startsWith('data:')) continue

        const dataStr = eventStr.replaceAll('data:', '').trim()

        if (dataStr === '[complete]') {
          emitter.emit('refreshAiTask')
        }

        if (dataStr === '[complete]') continue

        try {
          const content = dataStr

          if (content && content != '[complete]') {
            // 累积响应内容
            aiResponse += content
            // 更新最后一条AI消息的内容
            messages.value[aiMessageIndex].content = aiResponse
            // 滚动到底部
            nextTick(() => {
              scrollToBottom()
            })
          }
        } catch (e) {
          console.error('解析JSON失败:', e, '数据:', dataStr)
        }
      }
    }

    // 处理缓冲区中剩余的数据
    if (buffer.trim()) {
      const remainingData = buffer.trim()
      if (remainingData.startsWith('data:')) {
        const dataStr = remainingData.substring(5).trim()
        try {
          const content = dataStr
          if (content && content.trim()) {
            // 累积响应内容
            aiResponse += content
            // 更新最后一条AI消息的内容
            messages.value[aiMessageIndex].content = aiResponse
          }
        } catch (e) {
          console.error('解析剩余数据失败:', e)
        }
      }
    }
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Request was cancelled')
    } else {
      console.error('Error:', error)
      messages.value.push({
        role: 'system',
        content: `发生错误: ${error.message}`
      })
    }
  } finally {
    isLoading.value = false
    controller.value = null
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 其他方法保持不变
const messagesContainer = ref(null)
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const clear = () => {
  uuid.value = generateUUID()
  messages.value = []
  clickedButtons.value.clear()
}

const open = () => {
  panelDialog.value = true
  uuid.value = generateUUID()
  baseUrl.value = 'https://mcp.jzsaas.com'
}

// 在组件挂载时设置全局按钮点击处理函数
onMounted(() => {
  // 设置全局按钮点击处理函数
  window.handleAIButtonClick = (buttonElement) => {
    const buttonText = buttonElement.getAttribute('data-button-text')
    if (buttonText) {
      handleButtonClick(buttonText, buttonElement)
    }
  }
})

// 组件卸载时清理全局函数
onUnmounted(() => {
  if (window.handleAIButtonClick) {
    delete window.handleAIButtonClick
  }
})

defineExpose({ open })
</script>

<style scoped>
/* 主容器样式 */
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: linear-gradient(135deg, #fff8f0 0%, #fff4e6 100%);
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #ffe7cc;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-icon {
  color: #ff8c00;
  font-size: 16px;
}

.info-text {
  color: #d2691e;
  font-weight: 500;
}

.clear-btn {
  color: #666;
  transition: all 0.2s ease;
}

.clear-btn:hover {
  color: #ff8c00;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  max-width: 100%;
  background: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(255, 140, 0, 0.08);
  border: 1px solid #ffe7cc;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: linear-gradient(180deg, #fffbf7 0%, #fff8f0 100%);
  scroll-behavior: smooth;
}

.message {
  margin-bottom: 20px;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  max-width: 85%;
}

.message-wrapper.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-wrapper.ai {
  margin-right: auto;
}

.message-avatar {
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(255, 140, 0, 0.15);
}

.message-content {
  position: relative;
  border-radius: 16px;
  padding: 12px 16px;
  word-break: break-word;
  white-space: pre-wrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.message-content.user {
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.message-content.ai {
  background: #ffffff;
  color: #333;
  border: 1px solid #ffe7cc;
  border-bottom-left-radius: 4px;
}

.message-text {
  line-height: 1.5;
  margin-bottom: 4px;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  text-align: right;
}

.message-content.ai .message-time {
  color: #999;
}

.message-content.user .message-time {
  color: rgba(255, 255, 255, 0.8);
}

/* AI按钮样式 */
:deep(.ai-action-button) {
  display: flex;
  align-items: center;
  padding: 17px;
  margin: 0;
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(255, 140, 0, 0.3);
  position: relative;
  overflow: hidden;
  width: 100px;
  flex-shrink: 0;
  height: 40px;
}

:deep(.ai-action-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 140, 0, 0.4);
  background: linear-gradient(135deg, #ffa500 0%, #ffb84d 100%);
}

:deep(.ai-action-button:active) {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(255, 140, 0, 0.3);
}

:deep(.ai-action-button::before) {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s ease;
}

:deep(.ai-action-button:hover::before) {
  left: 100%;
}

:deep(.button-icon) {
  font-size: 16px;
  animation: pulse 2s infinite;
}

:deep(.button-text) {
  flex: 1;
  text-align: center;
}

:deep(.button-arrow) {
  font-size: 16px;
  font-weight: bold;
  transition: transform 0.3s ease;
}

:deep(.ai-action-button:hover .button-arrow) {
  transform: translateX(4px);
}

@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  color: #ff8c00;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  color: #333;
  margin: 0 0 8px 0;
  font-weight: 500;
}

.empty-subtext {
  font-size: 14px;
  color: #999;
  margin: 0;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.loading-text {
  color: #666;
  font-size: 14px;
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 6px;
  height: 6px;
  background: #ff8c00;
  border-radius: 50%;
  animation: loading-bounce 1.4s infinite;
  opacity: 0.3;
}

.loading-dots span:nth-child(1) {
  animation-delay: 0s;
}

.loading-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.loading-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes loading-bounce {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.3;
  }
  40% {
    transform: scale(1.2);
    opacity: 1;
  }
}

/* 输入区域样式 */
.chat-input-container {
  background: #ffffff;
  border-top: 1px solid #ffe7cc;
  padding: 16px 20px;
}

.input-wrapper {
  position: relative;
}

.chat-textarea {
  margin-bottom: 12px;
}

.chat-textarea :deep(.el-textarea__inner) {
  border: 1px solid #ffe7cc;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  transition: all 0.2s ease;
}

.chat-textarea :deep(.el-textarea__inner):focus {
  border-color: #ff8c00;
  box-shadow: 0 0 0 2px rgba(255, 140, 0, 0.1);
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-tip {
  color: #999;
}

.send-button {
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 500;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(255, 140, 0, 0.2);
}

.send-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 140, 0, 0.3);
}

.send-button:active {
  transform: translateY(0);
}

.send-button:disabled {
  background: #f5f7fa;
  color: #c0c4cc;
  transform: none;
  box-shadow: none;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #fff8f0;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(255, 140, 0, 0.2);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 140, 0, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    height: 400px;
  }

  .message-wrapper {
    max-width: 95%;
  }

  .panel-header {
    padding: 12px 16px;
  }

  .chat-messages {
    padding: 16px;
  }

  .chat-input-container {
    padding: 12px 16px;
  }

  :deep(.ai-action-button) {
    padding: 10px 16px;
    font-size: 13px;
  }
}
:deep(.clicked-button-placeholder) {
  display: none;
}
</style>
